"""
moonphase.py - Calculate Lunar Phase
Author: Sean B. Palmer, inamidst.com
Cf. http://en.wikipedia.org/wiki/Lunar_phase#Lunar_phase_calculation
"""

import math, decimal, datetime
dec = decimal.Decimal

class Calendar():
    def __init__(self, date = -1):
        if date == -1:
            self.date = datetime.datetime.now()
        else:
            self.date = date
        self.pos = self.position()

    def position(self, now=None): 
        if now is None: 
            now = self.date

        diff = now - datetime.datetime(2001, 1, 1)
        days = dec(diff.days) + (dec(diff.seconds) / dec(86400))
        lunations = dec("0.20439731") + (days * dec("0.03386959269"))
        self.lunations = lunations % dec(1)    
        return self.lunations

    def phase_name(self, pos = -1):
        if pos == -1:
            pos = self.pos

        index = (pos * dec(8)) + dec("0.5")
        index = math.floor(index)
        return {
            0: "New Moon", 
            1: "Waxing Crescent", 
            2: "First Quarter", 
            3: "Waxing Gibbous", 
            4: "Full Moon", 
            5: "Waning Gibbous", 
            6: "Last Quarter", 
            7: "Waning Crescent"
            }[int(index) & 7]

    def get_phase(self):
        return round(float(self.pos), 3) * 100

'''
def main(): 
    for i in range(2,20):
        pos = position(datetime.datetime(2009, 12, i))
        phasename = phase(pos)
    
        roundedpos = round(float(pos), 3)
        print "%s (%s)" % (phasename, roundedpos)
'''
    
if __name__=="__main__":
    print str(Calendar(datetime.datetime.now()).get_phase())
